package run_db_cmd;

require Exporter;


our @ISA = qw(Exporter);
our $VERSION = 1.00;
our @EXPORT = qw(   run_psql_file 
					run_psql_cmd 
					get_results_psql_cmd
					run_mysql_cmd);



use strict;
use warnings;
use DBI;
use DBD::Pg;
use Carp;
#use lib ("$FindBin::Bin/..", "/net/cpp-group/Leo/bin");
use db_parameters;



#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
#
#
#	Run commands
#
#		Wrapper to run a postgres, mysql query or a command line programme
#
#
sub run_psql_cmd
{
	my ($exec, $file, $verbose, $no_tab_format) = @_;

	# remove beginning white space and new lines
	$exec =~tr/\t\n/ /d;
	$exec =~ s/\s+/ /gm;

	my $cmd = "psql ";
	$cmd .= " -q " unless ($verbose);
	$cmd .= "  -t -A -F \"\t\" " unless ($no_tab_format);
	$cmd .= "-h $db_host -d $db_name -U $db_user -c \"$exec\"";
	if (defined $file)
	{
		# add redirection unless is pipe
		$file = '> '.$file unless ($file =~ /[ \t\n]*\|/);
		$cmd .= " $file";
	}
	print STDERR $cmd, "\n" if $verbose;
	system ($cmd)
		and croak "Failed to run psql:\n[ $cmd ]\n\n";
}

sub run_mysql_cmd
{
	my ($exec, $database, $file, $verbose) = @_;

	#
	#	Get DB parameters
	#
	my $cmd = "mysql -B -N  -u anonymous -h ensembldb.ensembl.org ";
	$cmd .= "-D \"$database\" -e \"$exec\"";
	if (defined $file)
	{
		# add redirection unless is pipe
		$file = '> '.$file unless ($file =~ /[ \t\n]*\|/);
		$cmd .= " $file";
	}
	print STDERR $cmd, "\n" if $verbose;
	system ($cmd)
		and croak "Failed to run mysql:\n[ $cmd ]\n\n";
}

sub get_results_psql_cmd
{
	my ($exec) = @_;

	#
	#	Get DB parameters
	#
	#remove beginning white space and new lines
	$exec =~tr/\t\n/ /d;
	$exec =~ s/\s+/ /gm;
	my $cmd = "psql -q -h $db_host -d $db_name -U $db_user -t -A -F \"\t\" -c \"$exec\"";
	return `$cmd`;
}

sub run_psql_file
{
	my ($file_name, $ignore, $verbose) = @_;

	#
	#	Get DB parameters
	#

	my $cmd = "psql ";
	$cmd .= " -q " unless ($verbose);
	$cmd .= "-h $db_host -d $db_name -U $db_user -t -A -f \"$file_name\"";
	system ($cmd)
		and croak "Failed to run psql:\n[ $cmd ]\n\n";
}

#
#	Run commands
#
#		Wrapper to run a postgres or mysql query
#
#
#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888










return 1;
